package com.tanhua.config.template;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.tanhua.config.properties.OssProperties;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {
    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    public String upload(String fileName, InputStream inputStream) throws Exception {

        String filePath = DateUtil.format(new Date(),"yyyy/MM/dd/HH")+"/"+ UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucketName(), filePath, inputStream);

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        ossClient.shutdown();

        return ossProperties.getUrl()+filePath;
    }
}
